package control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.el.ELContext;
import javax.faces.FactoryFinder;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Administrador;
import model.Aluno;
import model.Professor;
import model.Usuario;

/**
 * Servlet Filter implementation class SessaoFilter
 */
public class SessaoFilter implements Filter {

	private FilterConfig fc;
	private List<String> urlList = new ArrayList<String>();
	private List<String> urlListAlunos = new ArrayList<String>();
	private List<String> urlListProfessores = new ArrayList<String>();
	private List<String> urlListAdmin = new ArrayList<String>();

	/**
	 * Default constructor.
	 */
	public SessaoFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		fc = null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		FacesContext fc = getFacesContext(request, response);
		String url_atual = req.getRequestURI().substring(19);// Projeto2PWEB/
		ELContext el = fc.getELContext();
		LoginBean lb = (LoginBean) fc.getApplication().getELResolver()
				.getValue(el, null, "loginBean");
		String url_redir = "";
		boolean restricao = false;
		Usuario u = null;

		u = (Usuario) lb.getLogado();

		if (u instanceof Administrador) {
			url_redir = "/Projeto2PWEB/faces/painel.xhtml";
			restricao = urlListAdmin.contains(url_atual);
		} else if (u instanceof Aluno) {
			url_redir = "/Projeto2PWEB/faces/alunos.xhtml";
			restricao = urlListAlunos.contains(url_atual);
		} else if (u instanceof Professor) {
			url_redir = "/Projeto2PWEB/faces/professores.xhtml";
			restricao = urlListProfessores.contains(url_atual);
		}
		if (u == null) {
			url_redir = "/Projeto2PWEB/faces/index.xhtml";
			restricao = true;
		}

		if (!urlList.contains(url_atual)) {
			if (restricao) {
				res.sendRedirect(url_redir);
				return;
			}
		}

		if (u != null && url_atual.equals("/index.xhtml")) {
			res.sendRedirect(url_redir);
			return;
		}

		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		this.fc = fConfig;
		String urls = fc.getInitParameter("urllist");
		String urlsalu = fc.getInitParameter("urllistalu");
		String urlspro = fc.getInitParameter("urllistpro");
		String urlsadm = fc.getInitParameter("urllistadm");
		StringTokenizer tokenurls = new StringTokenizer(urls, ",");

		while (tokenurls.hasMoreTokens())
			urlList.add(tokenurls.nextToken());

		tokenurls = new StringTokenizer(urlsalu, ",");

		while (tokenurls.hasMoreTokens())
			urlListAlunos.add(tokenurls.nextToken());

		tokenurls = new StringTokenizer(urlspro, ",");

		while (tokenurls.hasMoreTokens())
			urlListProfessores.add(tokenurls.nextToken());

		tokenurls = new StringTokenizer(urlsadm, ",");

		while (tokenurls.hasMoreTokens())
			urlListAdmin.add(tokenurls.nextToken());
	}

	private abstract static class InnerFacesContext extends FacesContext {
		protected static void setFacesContextAsCurrentInstance(
				FacesContext facesContext) {
			FacesContext.setCurrentInstance(facesContext);
		}
	}

	private FacesContext getFacesContext(ServletRequest request,
			ServletResponse response) {
		// Try to get it first
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (facesContext != null)
			return facesContext;

		FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder
				.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
		LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
				.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
		Lifecycle lifecycle = lifecycleFactory
				.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
		ServletContext servletContext = ((HttpServletRequest) request)
				.getSession().getServletContext();
		facesContext = contextFactory.getFacesContext(servletContext, request,
				response, lifecycle);
		InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);

		return facesContext;
	}

}
